﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Extensions;
using Infrastructure.Model.UserAuth;
using Microsoft.AspNetCore.Http;
using UAParser;

namespace Infrastructure.Helper
{
    /// <summary>
    /// HTTP 请求工具类
    /// 提供同步/异步的 HTTP 请求能力及请求日志记录功能
    /// 注意：建议在生产环境中使用 IHttpClientFactory 替代直接实例化 HttpClient
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// 执行同步 HTTP POST 请求
        /// </summary>
        /// <param name="url">请求地址（必需）</param>
        /// <param name="postData">请求体数据（默认空）</param>
        /// <param name="contentType">内容类型（默认application/json）</param>
        /// <param name="timeOut">超时时间（秒，默认30）</param>
        /// <param name="headers">请求头字典（可选）</param>
        /// <returns>响应内容字符串</returns>
        /// <remarks>
        /// 同步方法可能导致线程池饥饿，建议优先使用异步版本
        /// </remarks>
        public static string HttpPost(
            string url,
            string postData = null,
            string contentType = "application/json",
            int timeOut = 30,
            Dictionary<string, string> headers = null)
        {
            // 空值处理逻辑
            postData ??= "";
            using HttpClient httpClient = new HttpClient();

            // 设置超时（需转换为TimeSpan）
            httpClient.Timeout = TimeSpan.FromSeconds(timeOut);

            // 添加请求头
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }

            // 构建请求内容
            using HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
            if (contentType != null)
            {
                httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            }

            // 同步执行请求（潜在死锁风险）
            HttpResponseMessage result = httpClient.PostAsync(url, httpContent).Result;
            return result.Content.ReadAsStringAsync().Result;
        }

        /// <summary>
        /// 执行异步 HTTP POST 请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">请求体数据</param>
        /// <param name="contentType">内容类型</param>
        /// <param name="timeOut">超时时间（秒）</param>
        /// <param name="headers">请求头字典</param>
        /// <returns>异步响应内容字符串</returns>
        public static async Task<string> HttpPostAsync(
            string url,
            string postData = null,
            string contentType = null,
            int timeOut = 30,
            Dictionary<string, string> headers = null)
        {
            postData ??= "";
            using HttpClient client = new HttpClient();
            client.Timeout = TimeSpan.FromSeconds(timeOut);

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            using HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
            if (contentType != null)
            {
                httpContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
            }

            // 异步执行请求
            var response = await client.PostAsync(url, httpContent);
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 执行同步 HTTP GET 请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="headers">请求头字典</param>
        /// <returns>响应内容字符串</returns>
        /// <remarks>
        /// 注意：默认添加了传统浏览器的 UserAgent，可能需要根据实际情况调整
        /// </remarks>
        public static string HttpGet(
            string url,
            Dictionary<string, string> headers = null)
        {
            using HttpClient httpClient = new HttpClient();

            // 默认请求头设置
            if (headers == null)
            {
                httpClient.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");
                httpClient.DefaultRequestHeaders.Add("UserAgent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            }
            else
            {
                foreach (var header in headers)
                {
                    httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }

            try
            {
                // 同步执行GET请求
                HttpResponseMessage result = httpClient.GetAsync(url).Result;
                return result.Content.ReadAsStringAsync().Result;
            }
            catch (Exception ex)
            {
                // 简单日志记录（建议使用ILogger）
                Console.WriteLine($"[HTTP请求异常] {url} | {ex.Message}");
                return string.Empty;
            }
        }

        /// <summary>
        /// 执行异步 HTTP GET 请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="headers">请求头字典</param>
        /// <returns>异步响应内容字符串</returns>
        public static async Task<string> HttpGetAsync(
            string url,
            Dictionary<string, string> headers = null)
        {
            using HttpClient client = new HttpClient();

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            var response = await client.GetAsync(url);
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 记录HTTP请求的登录信息
        /// </summary>
        /// <param name="context">HTTP上下文对象</param>
        /// <param name="status">登录状态</param>
        /// <param name="message">附加消息</param>
        /// <returns>系统登录信息实体</returns>
        public static SysLogininfo RecordLogInfo(  HttpContext context,string status,  string message)
        {
            // 获取客户端信息
            var clientInfo = context.GetClientInfo();

            return new SysLogininfo
            {
                Browser = clientInfo.Device.Family,
                OS = clientInfo.OS.ToString(),  // 更安全的转换方式
                Ipaddr = context.GetClientUserIp(),
                Msg = message,
                UserName = context.GetName(),
                Status = status,
                LoginLocation = ""  // 可扩展地理位置解析
            };
        }
    }
}
